package cn.gaaidou.dynamic.proxy.jdk.proxy;

import cn.gaaidou.dynamic.proxy.jdk.annotation.Params;
import cn.gaaidou.dynamic.proxy.jdk.annotation.Select;
import cn.gaaidou.dynamic.proxy.jdk.entity.User;
import lombok.extern.slf4j.Slf4j;

import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;

/**
 * 在debug的时候发现会出现 Method threw 'java.lang.NullPointerException' exception. Cannot evaluate com.sun.proxy.$Proxy0.toString()，
 * 但是不影响程序的正常运行
 *
 * @author Martin
 * @date 2021/7/14 19:08
 */
@Slf4j
public class MapperProxy implements InvocationHandler, Serializable {
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // 1、获取方法的sql配置信息
        Select selectSql = method.getAnnotation(Select.class);
        String sql = selectSql.value();

        // 2、把参数代入sql语句
        for (int index = 0; index < method.getParameters().length; index++) {
            Parameter v = method.getParameters()[index];
            Params params = v.getAnnotation(Params.class);
            sql = sql.replace(String.format("#{%s}", params.value()), args[index].toString());
        }

        // 3、模拟执行sql语句
        log.info("执行Sql语句: {}", sql);

        // 4、模拟返回结果
        User user = new User();
        user.setId(1L);
        user.setUsername("Martin");
        user.setPassword("123456");
        return user;
    }

}
